#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_L 200
#define MAX_W 200
typedef struct page
{
	int p_l, p_w; //页长 和 页宽
	int row, col; // 页面游标
	int page_index;
	char content[MAX_L][MAX_W];
};
FILE *fp = stdout;

int page_len, page_wid;
int page_num = 1;
void print_page(FILE *fp, page p);
page new_page(page &p)
{
	p.p_l = page_len;
	p.p_w = page_wid;
	p.row = 2;
	p.col = 2;
	p.page_index = page_num;
	for (int i = 0; i < page_len; i++)
	{
		for (int j = 0; j < page_wid; j++)
		{
			if (i == 0 || i == page_len - 1)
			{
				p.content[i][j] = '+';
			}
			else if (i == 1 || i == page_len - 2)
			{
				p.content[i][j] = '*';
			}
			else
			{
				if (j == 0 || j == page_wid - 1)
					p.content[i][j] = '*';
				else
					p.content[i][j] = ' ';
			}
		}
	}
	int ii = page_len - 1;
	int jj = page_wid / 2;

	int i = page_num % 10;
	int j = (page_num / 10) % 10;
	int k = (page_num / 100);
	p.content[ii][jj - 1] = k + '0';
	p.content[ii][jj] = j + '0';
	p.content[ii][jj + 1] = i + '0';
	page_num++;
}
void print_page(FILE *fp, page p)
{
	for (int i = 0; i < p.p_l; i++)
	{
		for (int j = 0; j < p.p_w; j++)
		{
			fputc(p.content[i][j], fp);
		}
		fputc('\n', fp);
	}
	fputc('\n', fp);
}

void insert(page &p, char word[])
{
	if (word[0] == '@')
	{
		if (p.row < p.p_l - 1)
		{
			p.row++;
			p.col = 4;
		}
		else
		{
			print_page(fp, p);
			new_page(p);
			insert(p, word);
		}
	}
	else
	{
		if (p.row < p.p_l - 2)
		{
			if (strlen(word) + p.col < p.p_w - 1)
			{
				for (int i = 0; i < strlen(word); i++)
				{
					p.content[p.row][p.col++] = word[i];
				}
				p.col++;
			}
			else
			{
				if (p.row < p.p_l - 2)
				{
					p.row++;
					p.col = 2;
					for (int i = 0; i < strlen(word); i++)
					{
						p.content[p.row][p.col++] = word[i];
					}
					p.col++;
				}
				else
				{
					print_page(fp, p);
					new_page(p);
					insert(p, word);
				}
			}
		}
		else
		{
			print_page(fp, p);
			new_page(p);
			insert(p, word);
		}
	}
}

int main()
{
	/*******************code*******************/
	// printf("intput page_len & page_wid:");
	// scanf("%d %d",&page_len,&page_wid);
	page_len = 40;
	page_wid = 70;
	page p;
	new_page(p);
	FILE *fp2 = fopen("book.txt", "r");
	char word[20];
	while (fscanf(fp2, "%19s", word) == 1)
	{
		insert(p, word);
	}

	print_page(stdout, p);
	/******************************************/
	printf("\n\n****************************\n");
	printf("Press Enter key to continue\n");
	getchar();
	return 0;
	/******************************************/
}
